// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: leon

#pragma once

#include <map>
#include <memory>
#include <regex>
#include <string>
#include <vector>

// internal
#include "coin2/exchange/base/feed/processor.h"
#include "coin2/exchange/base/market/enums.h"
#include "coin2/exchange/di/constant.h"
#include "coin2/exchange/util/json_util.h"

namespace coin2::exchange::btcturk::feed_v1 {
namespace impl {
using namespace coin2::exchange::base::symbology;
class BtcturkFeedProcessor : public base::feed::FeedParsingProcessor {
 public:
  explicit BtcturkFeedProcessor(
      const std::string& system_name,
      const coin2::exchange::di::ConstantInjection& ci,
      const feed::RawParserConfig& config)
      : FeedParsingProcessor(
            system_name,
            MarketExchangeApi{MarketType::Spot, ExchangeType::Btcturk, "v1"},
            ci,
            config,
            "cc/coin2/exchange/btcturk/feed_v1/schema.json") {}
  void OnTopicRecord(const base::executor::TopicRecordPacket& packet) override;
};
struct BtcturkChannel {
  int type;
  std::string channel;
  std::string native_symbol;
  std::string interval;

  static BtcturkChannel Parse(const rapidjson::Document& data) {
    int type = 0;
    std::string channel;
    std::string native_symbol;
    std::string interval;
    if (data.HasMember("type")) {
      type = data["type"].GetInt();
      if (type == 431 || type == 432 || type == 422) {
        channel = data["channel"].GetString();
        native_symbol = data["event"].GetString();
      } else {
        channel = "ignored";
      }
    } else if (data.HasMember("url")) {
      const std::string url = data["url"].GetString();
      if (url.find("klines/history") != std::string::npos) {
        auto parameters = base::feed::FeedParsingProcessor::GetRequestParameters(url);
        interval = parameters["resolution"];
        native_symbol = parameters["symbol"];
        channel = "?symbol={}&resolution=" + interval;  // kline_rest
      }
    }
    return BtcturkChannel{type, channel, native_symbol, interval};
  }
};
};  // namespace impl
using impl::BtcturkChannel;
using impl::BtcturkFeedProcessor;
}  // namespace coin2::exchange::btcturk::feed_v1
